<template>
  <div class="app-container">
    <div class="filter-container">
      <el-button size="small" type="primary" icon="el-icon-circle-plus" @click="clickAddTemplate()">新增</el-button>
      <el-button size="small" type="danger" icon="el-icon-delete" @click="clickMultipleDelete">批量删除</el-button>
    </div>
    <el-dialog
      title="删除商品"
      :visible.sync="dialogVisibles"
      width="30%">
      <div class="editGoodsGounp">
        请谨慎操作
      </div>
      <span slot="footer" class="dialog-footer">
          <el-button size="small" @click="dialogVisible = false">取 消</el-button>
          <el-button size="small" type="primary" @click="makeSureDetele()">确 定</el-button>
      </span>
    </el-dialog>
    <el-table :data="currentTemplates" ref="multipleTable" @selection-change="handleSelectionChange" border>
      <el-table-column type="expand">
        <template slot-scope="scope">
          <el-form
            label-position="right"
            inline
            class="table-expand"
          >
            <el-form-item label="标题：" style="width:100%">
              <span>{{scope.row.templateName}}</span>
            </el-form-item>
            <el-form-item label="运送方式：">
              <span>快递</span>
            </el-form-item>
            <el-form-item label="计价方式：">
              <span>{{scope.row.templateType==1?'按重计费':'按件计费'}}</span>
            </el-form-item>
            <el-form-item label style="width:100%">
              <br>
            </el-form-item>
            <el-form-item label="首(单位)：">
              <span>{{scope.row.firstAmount}}</span>
            </el-form-item>
            <el-form-item label="运费(元)：">
                <span>{{scope.row.firstPrice|divideFilter}}</span>
            </el-form-item>
            <el-form-item label="续(单位)：">
                <span>{{scope.row.continueAmount}}</span>
            </el-form-item>
            <el-form-item label="续费(元)：">
                <span>{{scope.row.continuePrice|divideFilter}}</span>
            </el-form-item>
          </el-form>
        </template>
      </el-table-column>
      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column label="标题" min-width="50%" align="center">
        <template slot-scope="scope">
          <span>{{scope.row.templateName}}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" min-width="30%" align="center">
        <template slot-scope="scope">
          <el-button plain type="primary" size="mini" @click="clickEditTemplate(scope.$index, scope.row)">编辑</el-button>
          <el-button plain size="mini" type="danger" @click="clickDeleteTemplate(scope.$index, scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <list-pagination :total="total" :page="page" :pageSize="pageSize" :handleSizeChange="handleSizeChange" :handleCurrentChange="handleCurrentChange"></list-pagination>
    <el-dialog :before-close="handleClose('freightTemplate')" title="操作提示" :visible.sync="dialogFormVisible" width="600px">
      <el-form
        :rules="rules"
        ref="freightTemplate"
        :model="freightTemplate"
        label-position="right"
        style="width: 400px; margin-left:50px;"
      >
        <el-form-item :label="freightTemplateTitles.templateTitle" prop="templateName" label-width="140px">
          <el-input v-model="freightTemplate.templateName" placeholder="请输入模板名称"></el-input>
        </el-form-item>
        <el-form-item
          :label="freightTemplateTitles.setFreightTypeTitle"
          label-width="140px"
        ><span style="dont-size:14px;font-weight:500">买家承担运费</span>
        </el-form-item>
          <el-form-item label="计费规则：" prop="templateType" label-width="140px">
            <template>
              <el-radio-group v-model="freightTemplate.templateType" @change="changeTemplateType">
                <el-radio :label="2">按件计费</el-radio>
                <el-radio :label="1">按重计费</el-radio>
              </el-radio-group>
            </template>
          </el-form-item>
          <div v-if="freightTemplate.templateType === 2">
            <el-form-item prop="firstAmount">
              <template>
                <el-input
                  placeholder="请输入内容"
                  v-model="freightTemplate.firstAmount"
                  class="input-with-select"
                  onkeypress="return( /[\d]/.test(String.fromCharCode(event.keyCode) ) )"
                >
                  <label slot="prepend" class="prependLabel">首件:</label>
                  <label slot="append" class="appendLabel">件</label>
                </el-input>
                </template>
            </el-form-item>
            <el-form-item prop="firstPrice">
              <template>
                <el-input
                  placeholder="请输入内容"
                  v-model="freightTemplate.firstPrice"
                  class="input-with-select"
                >
                  <label slot="prepend" class="prependLabel">首件运费:</label>
                  <label slot="append" class="appendLabel">RB</label>
                </el-input>
                </template>
            </el-form-item>
            <el-form-item prop="continueAmounts">
              <template>
                <el-input
                  placeholder="请输入内容"
                  v-model="continueAmounts"
                  class="input-with-select"
                  :disabled="true"
                >
                  <label slot="prepend" class="prependLabel">每增加产品数:</label>
                  <label slot="append" class="appendLabel">件</label>
                </el-input>
              </template>
            </el-form-item>
            <el-form-item prop="continuePrice">
              <template>
                <el-input
                  placeholder="请输入内容"
                  v-model="freightTemplate.continuePrice"
                  class="input-with-select"
                >
                  <label slot="prepend" class="prependLabel">续加运费:</label>
                  <label slot="append" class="appendLabel">RB/件</label>
                </el-input>
              </template>
            </el-form-item>
          </div>
          <div v-if="freightTemplate.templateType === 1">
            <el-form-item prop="firstAmount">
              <template>
                <el-input
                  placeholder="请输入内容"
                  v-model.number="freightTemplate.firstAmount"
                  class="input-with-select"
                >
                  <label slot="prepend" class="prependLabel">首重:</label>
                  <label slot="append" class="appendLabel">kg</label>
                </el-input>
              </template>
            </el-form-item>
            <el-form-item prop="firstPrice">
              <template>
                <el-input
                  placeholder="请输入内容"
                  v-model="freightTemplate.firstPrice"
                  class="input-with-select"
                >
                  <label slot="prepend" class="prependLabel">首重运费:</label>
                  <label slot="append" class="appendLabel">RB</label>
                </el-input>
               </template>
            </el-form-item>
            <el-form-item prop="continueAmount">
              <template>
                <el-input
                  placeholder="请输入内容"
                  v-model="freightTemplate.continueAmount"
                  class="input-with-select"
                >
                  <label slot="prepend" class="prependLabel">每增加重量:</label>
                  <label slot="append" class="appendLabel">kg</label>
                </el-input>
              </template>
            </el-form-item>
            <el-form-item prop="continuePrice">
              <template>
                <el-input
                  placeholder="请输入内容"
                  v-model="freightTemplate.continuePrice"
                  class="input-with-select"
                >
                  <label slot="prepend" class="prependLabel">续加运费:</label>
                  <label slot="append" class="appendLabel">RB/kg</label>
                </el-input>
              </template>
            </el-form-item>
          </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click="dialogFormVisible=false">取 消</el-button>
        <el-button size="small" type="primary" @click="clickConfirmDialog(freightTemplate)">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import list from '@/mixins/List'
import listPagination from '@/components/ListPagination'
import { divide } from '@/filter/index'
import { getAddressListByPage, addTemplate, updateTemplate, deleteTemplate } from '@/api/freightTemplate'
export default {
  mixins: [list],
  data () {
    return {
      dialogFormVisible: false,
      dialogVisibles: false,
      id: '',
      dialogStatus: '',
      disabledIf: '',
      multipleSelection: [],
      dataListId: [],
      rowAccount: '',
      continueAmounts: 1,
      dialogStatusMap: {
        update: 'Edit',
        create: 'Create'
      },
      freightTemplateTitles: {
        templateTitle: '模板名称：',
        transportMode: '运送方式：',
        setFreightTypeTitle: '设置运费类型：'
      },
      freightTemplate: {
        templateType: '', // 计费规则
        templateName: '', // 模板名称
        firstAmount: '',
        firstPrice: '',
        continueAmount: '', // 续加重量/件数
        continuePrice: ''// 续加运费
      },
      currentTemplates: [],
      selectedTemplates: [],
      regionOptions: [],
      freightTypeOptions: [
        {
          value: 1,
          label: '卖家承担运费'
        },
        {
          value: 2,
          label: '买家承担运费'
        }
      ],
      opartion: '',
      rules: {
        templateName: [
          { required: true, message: '请输入模版名称', trigger: 'change' },
          { min: 0, max: 20, message: '长度在20个字符内', trigger: 'change' }
        ],
        support: [
          { required: true, message: '请设置运费类型', trigger: 'change' }
        ],
        templateType: [
          { required: true, message: '请选择计费规则', trigger: 'change' }
        ],
        firstAmount: [
          { required: true, message: '请输入首件件数', trigger: 'change' }
        ],
        firstPrice: [
          { required: true, message: '请输入首重运费', trigger: 'change' }
        ],
        continueAmount: [
          { required: true, message: '请输入每增加重量', trigger: 'change' }
        ],
        continueAmounts: [
          { required: false, message: '请输入每增加重量', trigger: 'change' }
        ],
        continuePrice: [
          { required: true, message: '请输入续加运费', trigger: 'change' }
        ]
      }
    }
  },
  components: {
    listPagination
  },
  watch: {
    freightTemplate: {
      handler: function () {

      }
    },
    multipleSelection: function () {
      let arr = []
      for (let i in this.multipleSelection) {
        arr.push(this.multipleSelection[i].id)
      }
      this.dataListId = arr
    }
  },
  created () {
    this.getList()
  },
  methods: {
    // methods of netwoking
    getList () {
      getAddressListByPage({
        pageNo: this.page,
        pageSize: this.pageSize
      }).then(result => {
        this.currentTemplates = result.data.dataList
        this.total = result.data.total
      }).catch(err => {
        console.log(err)
      })
    },
    changeTemplateType () {
      // var target = this.freightTemplate.firstAmount
      // if (target !== undefined && target.indexOf('.') !== -1) {
      //   console.log(1)
      // }
    },
    handleClose () {

    },
    makeSureDetele () {

    },
    editTemplate () {

    },

    deleteTemplates () {
      deleteTemplate({ 'ids': this.id })
        .then(result => {
          if (result.code === 200) {
            this.dialogFormVisible = false
            this.getList()
            this.$message({
              type: 'success',
              message: '删除成功!'
            })
          }
        })
        .catch(err => {
          throw err
        })
    },
    resetFreightTemplate () {

    },
    clickAddTemplate (freightTemplate) {
      this.freightTemplate = {}
      if (this.$refs['freightTemplate'] !== undefined) {
        this.$refs['freightTemplate'].resetFields()
      }
      this.dialogFormVisible = true
      this.opartion = '新增'
    },
    clickEditTemplate (index, row) {
      console.log(JSON.parse(JSON.stringify(row)))
      this.freightTemplate = JSON.parse(JSON.stringify(row))
      this.freightTemplate.firstPrice = divide(this.freightTemplate.firstPrice)
      this.freightTemplate.continuePrice = divide(this.freightTemplate.continuePrice)
      this.freightTemplate.templateId = row.id
      this.opartion = '编辑'
      this.dialogFormVisible = true
    },
    clickDeleteTemplate (index, row) { // 单次操作
      this.$confirm('此操作将永久删除改模版, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.id = row.id
          this.opartion = '新增'
          this.deleteTemplates()
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    clickMultipleDelete () { // 批量删除
      if (this.dataListId.length === 0) {
        this.$message('请先勾选您需操作的商品')
        return
      }
      var str = ''
      for (let item of this.dataListId) {
        str += item + '|'
      }
      str = str.substr(0, str.length - 1)
      console.log(str)
      this.$confirm('此操作将永久删除所选模版, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteTemplate({ 'ids': str }).then(res => {
          if (res.code === 200) {
            this.dialogFormVisible = false
            this.getList()
            this.$message({
              type: 'success',
              message: '删除成功!'
            })
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    templateType () {
      console.log(1)
    },
    clickConfirmDialog (freightTemplate) { // 新增/编辑
      this.$refs['freightTemplate'].validate((valid) => {
        if (valid) {
          if (this.freightTemplate.templateType === 2) {
            this.freightTemplate.continueAmount = this.continueAmounts
          } else {
            this.freightTemplate.continueAmount = this.freightTemplate.continueAmount
          }
          this.freightTemplate.firstPrice = this.freightTemplate.firstPrice * 100
          this.freightTemplate.continuePrice = this.freightTemplate.continuePrice * 100
          if (this.opartion === '新增') {
            addTemplate(this.freightTemplate).then(res => {
              if (res.code === 200) {
                this.getList()
                this.dialogFormVisible = false
                this.$message.success('操作成功')
              }
            })
          } else if (this.opartion === '编辑') {
            updateTemplate(this.freightTemplate).then(res => {
              if (res.code === 200) {
                this.dialogFormVisible = false
                this.getList()
                this.$message.success('操作成功')
              }
            })
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    handleSelectionChange (val) {
      this.multipleSelection = val
    },
    handleCurrentChange (value) {
      this.page = value
      this.getTemplates()
    },
    handleSizeChange (value) {
      this.pageSize = value
      this.getTemplates()
    }
  }
}
</script>

<style>
.prependLabel {
  text-align: center;
  width: 80px;
  display: inline-block;
}
.appendLabel {
  text-align: center;
  width: 60px;
  display: inline-block;
}
.table-expand {
  font-size: 0;
}
.table-expand label {
  width: 90px;
  color: #99a9bf;
}
.table-expand .el-form-item {
  margin-right: 0;
  margin-bottom: 0;
  width: 50%;
}
</style>
